package com.sa07.ui.config;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.sa07.config.IConfigInit;
import com.sa07.config.IConfigInitManager;
import com.sa07.config.OracleConfigInit;
import com.sa07.config.TestItemInit;
import com.sa07.config.UserArgsConfigInit;

/**
 * 异步的配置初始化管理实现(采用多线程方式异步初始化配置，提高效率)
 * 
 * @author Long.shangbo
 *
 * 2014-2-15 上午1:38:11
 */
public class AsynConfigInitManager implements IConfigInitManager {
	
	/**
	 * 初始化任务数量(有多少任务就定义多少)
	 */
	private int initTaskCount = 5;
	
	/**
	 * 计数器，控制任务
	 */
	private CountDownLatch ctrl = null;
	
	/**
	 * 线程池
	 */
	private ExecutorService excutor = null;
	
	public AsynConfigInitManager(){
		
		this.ctrl = new CountDownLatch(initTaskCount);
		this.excutor = Executors.newFixedThreadPool(initTaskCount);
	}
	
	@Override
	public void init() {
		//启动任务初始化菜单栏
		excutor.execute(new InitTask(new MenuConfigInit(), ctrl));
		//启动任务初始化工具栏
		excutor.execute(new InitTask(new StatusBarConfigInit(), ctrl));
		//初始化oracle数据库
		excutor.execute(new InitTask(new OracleConfigInit(), ctrl));
		//测试配置文件初始化
		excutor.execute(new InitTask(new TestItemInit(), ctrl));
		//用户设置
		excutor.execute(new InitTask(new UserArgsConfigInit(), ctrl));
		
		excutor.shutdown();
		
		try {
			ctrl.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化配置任务类
	 * 
	 * @author Long.shangbo
	 *
	 * 2014-2-15 上午1:42:47
	 */
	private class InitTask implements Runnable{
		
		private IConfigInit configInit = null;
		
		private CountDownLatch ctrl = null;
		
		public InitTask(IConfigInit configInit, CountDownLatch ctrl){
			this.configInit = configInit;
			this.ctrl = ctrl;
		}

		@Override
		public void run() {
			configInit.init();
			ctrl.countDown();
		}
		
	}
}
